package com.dearcocoa.controller;

import com.dearcocoa.common.BaseResult;
import com.dearcocoa.common.Status;
import com.dearcocoa.exception.SecurityException;
import com.dearcocoa.payload.LoginRequest;
import com.dearcocoa.utils.JwtUtil;
import com.dearcocoa.vo.JwtResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 *
 * </p>
 *
 * @Package: com.dearcocoa.controller
 * @ClassName: AuthController
 * @Author: shengong
 * @Date: Created in 2020-08-08 21:14
 * @Version: V1.0
 * @Description: TODO
 */
@Slf4j
@RestController
@RequestMapping("api/auth")
public class AuthController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登录
     * @param loginRequest
     * @return
     */
    @PostMapping("login")
    public BaseResult login(@Valid @RequestBody LoginRequest loginRequest) {
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUserNameOrPhoneOrEmail(), loginRequest.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        String jwt = jwtUtil.createJWT(authenticate, loginRequest.isRememberMe());
        return BaseResult.ofSuccess(new JwtResponse(jwt));
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @PostMapping("logout")
    public BaseResult logout(HttpServletRequest request) {
        try {
            jwtUtil.invildJWT(request);
        } catch (SecurityException exception) {
            throw new SecurityException(Status.UNAUTHORIZED);
        }
        return BaseResult.ofStatus(Status.LOGOUT);
    }
}
